import pymysql


class DButils:
    def __init__(self, host, user, password, database, port):
        self.cursor = None
        self.conn = None
        self.host = host
        self.user = user
        self.password = password
        self.database = database
        self.port = port

    def connect(self):
        self.conn = pymysql.connect(
            host=self.host,
            user=self.user,
            password=self.password,
            database=self.database,
            port=self.port,
        )
        self.cursor = self.conn.cursor()

    def close(self):
        if self.cursor:
            self.cursor.close()
        if self.conn:
            self.conn.close()

    def update(self, sql, params=None):
        try:
            with self.connect() as conn:
                with conn.cursor() as cursor:
                    cursor.execute(sql, params)
                    conn.commit()
                    print("操作成功")
        except Exception as e:
            print("操作失败，", e)
        finally:
            self.close()

    def select(self, sql, params=None):
        try:
            with self.connect() as conn:
                with conn.cursor() as cursor:
                    cursor.execute(sql, params)
                    data = self.cursor.fetchall()
                    # for row in data:
                    #     print(row)
                    return data
        except Exception as e:
            print("查询失败，", e)
        finally:
            self.close()
